package cn.com.wxd.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.dao.frame.AttachDao;
import cn.com.wxd.service.attach.entity.AttachInfo;
import cn.com.wxd.service.attach.AttachConfEntity;
import cn.com.wxd.service.attach.AttachUtil;
import cn.com.wxd.common.CharUtil;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.common.JsonUtil;
import cn.com.wxd.common.file.ImageUtil;
import cn.com.wxd.common.file.MyFileUtil;
import cn.com.wxd.util.SpringContextHolder;

/**
 * Title:用户头像上传
 * Description:cn.com.wxd.servlet
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2015-12-25 下午5:47:03
 *
 * @author WangXuDong
 * @version 1.0
 */
public class UserPicUploadServlet extends HttpServlet {
    /**
     *
     */
    private static final long serialVersionUID = 2430650484910768876L;
    private static final Logger log = LoggerFactory.getLogger(UserPicUploadServlet.class);

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException {

        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException {
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        String picX = "";  //图片裁剪的起点X
        String picY = "";    //图片裁剪的起点Y
        String picWidth = ""; //图片裁剪宽度
        String picHight = ""; //图片裁剪高度
        String LastheadImg = ""; //裁剪的图片地址
        String isCutImg = "";//是否进行裁剪裁剪
        AttachConfEntity ace = null;
        try {
            ace = AttachUtil.instance().getAttachConfByParamName("userheadpic");
        } catch (IOException e) {
            log.info("头像上传配置文件参数：userheadpic没有配置" + e.getMessage(), e);
        } catch (DocumentException e) {
            log.info("头像上传配置文件参数：userheadpic配置错误" + e.getMessage(), e);
        }
        String savePath = ace.getPath() + File.separator + DateUtil.getDatetimeStr("yyyyMMdd") + File.separator;
        File dirfile = new File(savePath);
        if (!dirfile.exists()) {
            dirfile.mkdirs();
        }
        List<AttachInfo> fileInfoList = new ArrayList<AttachInfo>();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(2 * 1024 * 1024); // 设定使用内存超过2M时，将产生临时文件并存储于临时目录中。
        factory.setRepository(new File(ace.getPath() + "/temp"));  // 设定存储临时文件的目录。
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<?> items = null;
        try {
            boolean isMult = ServletFileUpload.isMultipartContent(request);   //是否是enctype=multipart/form-data表单
            if (isMult) {
                items = upload.parseRequest(request);
            }
        } catch (FileUploadException e1) {
            log.error(e1.getMessage());
        }
        if (items != null) {
            Iterator<?> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    String name = item.getFieldName();
                    if (name.equalsIgnoreCase("headX")) {
                        picX = item.getString();
                    }
                    if (name.equalsIgnoreCase("headY")) {
                        picY = item.getString();
                    }
                    if (name.equalsIgnoreCase("headWidth")) {
                        picWidth = item.getString();
                    }
                    if (name.equalsIgnoreCase("headHeight")) {
                        picHight = item.getString();
                    }
                    if (name.equalsIgnoreCase("LastheadImg")) {
                        LastheadImg = item.getString();
                    }
                    if (name.equalsIgnoreCase("isCutImg")) {
                        isCutImg = item.getString();
                    }
                } else {  //如果是文件域
                    AttachInfo fue = new AttachInfo();  //new一个文件信息对象

                    String fileName = item.getName();
                    String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
                    if (isImgFile(extName) == true) {
                        fue.setFileName(fileName);
                        fue.setSize(String.valueOf(item.getSize()));
                        fue.setPath(savePath);
                        if (fileName != null) {
                            String endstr = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                            fue.setExtName(endstr);
                            fileName = DateUtil.getTimestamp() + CharUtil.getRanNumber(4) + endstr;
                        }
                        //设置文件访问路径。。此路径并非正真的访问路径，但是这里返回一个正常访问的地址
                        fue.setAccessPath(request.getContextPath() + "/Stream/" + ace.getParamname() + "/" + fileName);
                        fue.setUpFileName(fileName);
                        try {
                            File uploadedFile = new File(savePath, fileName);
                            OutputStream os = new FileOutputStream(uploadedFile);
                            InputStream is = item.getInputStream();
                            byte buf[] = new byte[1024];// 可以修改 1024 以提高读取速度
                            int length = 0;
                            while ((length = is.read(buf)) > 0) {
                                os.write(buf, 0, length);
                            }
                            // 关闭流
                            os.flush();
                            os.close();
                            is.close();
                            fileInfoList.add(fue);  //添加到列表中
                        } catch (Exception e) {
                            log.info("文件上传出现问题：" + e.getMessage());
                        }
                        if (ace.isRecorddb()) {
                            try {
                                String fileid = DateUtil.getTimestamp() + CharUtil.getRanNumber(2);
                                fue.setFileId(fileid);
                                AttachDao attachDao = (AttachDao) SpringContextHolder.getBean("attachDao");
                                attachDao.insertAttachInfo(fue);
                            } catch (Exception e) {
                                    log.error("文件上传信息存入数据库失败!", e);
                            }
                        }
                    }

                }
            }
        } else {
            picX = request.getParameter("picX");
            picY = request.getParameter("picY");
            picWidth = request.getParameter("picWidth");
            picHight = request.getParameter("picHeight");
            LastheadImg = request.getParameter("LastheadImg");
            isCutImg = request.getParameter("isCutImg");
        }
        if (CharUtil.stringParsInt(picWidth) < 0) {
            picWidth = "100";
        }
        if (CharUtil.stringParsInt(picHight) < 0) {
            picHight = "100";
        }
        if (CharUtil.stringParsInt(picX) < 0) {
            picX = "0";
        }
        if (CharUtil.stringParsInt(picY) < 0) {
            picY = "0";
        }
        if (isCutImg != null && isCutImg.equalsIgnoreCase("true")) { //容许裁剪图片
            if (fileInfoList.size() > 0) {  //裁剪刚才上传的图片
                String cfilePath = fileInfoList.get(0).getPath();
                String cfileName = fileInfoList.get(0).getUpFileName();
                ImageUtil iu;
                try {
                    iu = new ImageUtil(cfilePath + cfileName);
                    iu.cutImage(cfilePath + cfileName, CharUtil.stringParsInt(picX), CharUtil.stringParsInt(picY),
                            CharUtil.stringParsInt(picWidth), CharUtil.stringParsInt(picHight));//裁剪并重新替换原来上传的图片
                } catch (IOException e) {
                    log.error("裁剪图片出现异常!" + e.getMessage());
                }
            } else { //裁剪指定路劲的图片 //返回了修改的图片文件信息
                if (LastheadImg != null && !LastheadImg.trim().equals("")) {     //没有上传新文件直接进行裁剪
                    try {
                        //修改的文件的信息
                        AttachInfo fue = new AttachInfo();
                        String[] param = LastheadImg.split("\2");
                        fue.setUpFileName(param[1]);
                        fue.setExtName(param[1].substring(param[1].lastIndexOf(".") + 1));
                        fue.setPath(param[0]);
                        fileInfoList = new ArrayList<>();
                        if (isImgFile(fue.getExtName())) {
                            //裁剪图片
                            ImageUtil iu = new ImageUtil(fue.getPath() + File.separator + fue.getUpFileName());
                            //生成新的文件和文件名
                            String outPath = ace.getPath() + File.separator + DateUtil.getDatetimeStr("yyyyMMdd")
                                    + File.separator;
                            String newUpfileName =
                                    DateUtil.getTimestamp() + CharUtil.getRanNumber(4) + "." + fue.getExtName();
                            iu.cutImage(outPath + newUpfileName, CharUtil.stringParsInt(picX),
                                    CharUtil.stringParsInt(picY),
                                    CharUtil.stringParsInt(picWidth), CharUtil.stringParsInt(picHight)
                            );//裁剪后替换原来的图片
                            //删除之前的图片
                            MyFileUtil.deleteFile(new File(fue.getPath() + File.separator + fue.getUpFileName()));
                            //重新放入新的信息
                            fue.setPath(outPath);
                            fue.setUpFileName(newUpfileName);
                            fue.setAccessPath(
                                    request.getContextPath() + "/Stream/" + ace.getParamname() + "/" + newUpfileName);
                            fileInfoList.add(fue);
                        }
                    } catch (IOException e) {
                        log.error("图片裁剪出现问题" + e.getMessage());
                        return;
                    }
                }
            }
        }
        String json = JsonUtil.objectToJson(fileInfoList);
        if (out != null) {
            out.print(json);
            out.flush();
            out.close();
        }
    }

    private boolean isImgFile(String extName) {
        if (extName == null) {
            return false;
        }
        if (extName.lastIndexOf(".") >= 0) {
            extName = extName.substring(extName.lastIndexOf(".") + 1);
        }
        if (extName.equalsIgnoreCase("png") || extName.equalsIgnoreCase("jpeg") || extName.equalsIgnoreCase("bmp")
                || extName.equalsIgnoreCase("gif") || extName.equalsIgnoreCase("jpg")) {
            return true;
        }
        return false;
    }
}
